package public

import (
	"context"

	"device-admin/config/mysql"
	"device-admin/internal/app/grpc/client"
	"device-admin/internal/app/grpc/protoc/system_admin"
	"device-admin/internal/models"

	"192.168.1.75/go-pkg/logx"
)

type DeviceLocationType struct {
	CityID   string `json:"city_id" gorm:"column:city_id"`
	CityName string `json:"city_name" gorm:"column:city_name"`
}

// LocationDistribution 设备位置分布
func LocationDistribution() []DeviceLocationType {
	deviceLocation := []DeviceLocationType{}
	db := mysql.NewDB()
	// 设备和位置联通，统计每个市的设备数量
	var cityIDs []string
	tx := db.Model(&models.Device{})
	tx.Joins("JOIN location ON device.location_id = location.id").Distinct().Pluck("location.city_id", &cityIDs)
	// 获取商户列表
	systemAdminClient, err := client.GetSystemAdminClient()
	if err != nil {
		logx.Error(context.Background(), "GetSystemAdminClient err", logx.Err(err))
	}
	rsp, err := systemAdminClient.AreaList(context.Background(), &system_admin.AreaLisRequest{
		AreaIDs: cityIDs,
	})
	if err != nil {
		logx.Error(context.Background(), "GetSystemAdminClient AreaList err", logx.Err(err))
	}
	for _, area := range rsp.Areas {
		deviceLocation = append(deviceLocation, DeviceLocationType{
			CityID:   area.ID,
			CityName: area.Name,
		})
	}
	return deviceLocation
}
